import fetch from "node-fetch"
import common from '../../lib/common/common.js'

/**
 * 作者：千奈千祁(2632139786)
 * Gitee主页：Gitee.com/QianNQQ
 * Github主页：Github.com/QianNQQ
 * 
 * 该插件所有版本发布于 该仓库(https://gitee.com/qiannqq/yunzai-plugin-JS)
 * 本插件及该仓库的所有插件均遵循 GPL3.0 开源协议
 * 
 * 请勿使用本插件进行盈利等商业活动行为
 */

let gsUrl = `https://hk4e-api.mihoyo.com/common/hk4e_cn/announcement/api/getAnnList?game=hk4e&game_biz=hk4e_cn&lang=zh-cn&bundle_id=hk4e_cn&platform=pc&region=cn_gf01&level=55&uid=100000000`
// let srUrl = `https://hkrpg-api.mihoyo.com/common/hkrpg_cn/announcement/api/getAnnList?game=hkrpg&game_biz=hkrpg_cn&lang=zh-cn&auth_appid=announcement&authkey_ver=1&bundle_id=hkrpg_cn&channel_id=1&level=65&platform=pc&region=prod_gf_cn&sdk_presentation_style=fullscreen&sdk_screen_transparent=true&sign_type=2&uid=100000000`

// 要推送的群 格式 [123456789, 987654321]
// OPENID格式(QQ-Group-Bot、QQ频道Bot) [`1A2B3C4D`, `5E6F7G8H`]
let pushGroups = []
// 要推送的Botqq
let Botqq = 123456789
// 剩余几天开始推送 默认一天
let yujing = 1
// cron表达式 推送时间
let pushtime = `0 0 10 * * ?`

export class example2 extends plugin {
    constructor () {
      super({
        name: '活动到期推送',
        dsc: '活动到期推送',
        event: 'message',
        priority: 5000,
        rule: [
          {
            reg: '^#手动推送活动$',
            fnc: 'EventPush',
            permission: 'master'
          }
        ]
      });
      this.task = {
        cron: pushtime,
        name: 'EventPush',
        fnc: this.EventPush.bind(this)
      }
    }
    async EventPush(){
        let gshd
        try {
            gshd = await fetch(gsUrl)
            gshd = await gshd.json()
        } catch (error) {
            logger.error(`获取原神活动数据失败：${error}`)
            return true
        }
        if(!gshd) {
            logger.error(`获取原神活动数据失败`)
            return true
        }
        let hdlist = []
        for (let item of gshd.data.list[1].list) {
            if(item.tag_label.includes(`活动`) && !item.title.includes(`传说任务`)) hdlist.push(item)
        }
        for (let item of hdlist) {
            let endDt = item.end_time
            endDt = endDt.replace(/\s/, `T`)
            let todayt = new Date()
            endDt = new Date(endDt)
            let sydate = await this.calculateRemainingTime(todayt, endDt)
            if(sydate.days <= yujing) {
                let logtime = pushGroups.length * 10
                logger.mark(`[活动到期推送]:开始推送活动到期信息，预计${logtime}秒完成`)
                for (let items of pushGroups) {
                    let msgList = [
                        `【原神活动即将结束通知】`,
                        `\n活动:${item.subtitle}`,
                        segment.image(item.banner),
                        `描述:${item.title}`,
                        `\n活动剩余时间:${sydate.days}天${sydate.hours}小时${sydate.minutes}分钟${sydate.seconds}秒`,
                        `\n活动结束时间:${item.end_time}`
                    ]
                    Bot[Botqq].pickGroup(items).sendMsg(msgList)
                        .then(() => logger.mark(`[活动到期推送]:群${items}推送完成`))
                        .catch((err) => logger.error(`[活动到期推送]:群${items}推送失败\n错误码:${err.code}\n错误信息:${err.message}`))
                    await common.sleep(10000)
                }
            }
        }
        
    }
    /**
     * 计算起始时间与目标时间的剩余时间
     * @param {*} startTime 起始时间
     * @param {*} targetTime 目标时间
     * @returns 
     */
    async calculateRemainingTime(startDate, endDate) {
        const difference = endDate - startDate;
        
        const days = Math.floor(difference / (1000 * 60 * 60 * 24));
        const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((difference % (1000 * 60)) / 1000);
        
        return { days, hours, minutes, seconds };
    }
}